package com.webproject.shop.service.impl;

import com.webproject.shop.common.BusinessException;
import com.webproject.shop.common.ErrorCode;
import com.webproject.shop.dao.UserMapper;
import com.webproject.shop.pojo.User;
import com.webproject.shop.service.UserService;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService, ErrorCode {
    @Autowired
    private UserMapper userMapper;

    //注册模块
    @Override
    public void register(User user) {
        if (user == null) {
            throw new BusinessException(PARAMETER_ERROR, "参数不能为空！");
        }

        try {
            userMapper.insert(user);
        } catch (DuplicateKeyException e) {
            throw new BusinessException(PARAMETER_ERROR, "该用户名已注册！");
        }
    }

    //登录模块
    @Override
    public User login(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BusinessException(PARAMETER_ERROR, "参数不合法！");
        }

        User user = userMapper.selectByPrimaryKey(username);
        if (user == null || !StringUtils.equals(password, user.getPassword())) {
            throw new BusinessException(USER_LOGIN_FAILURE, "账号或密码错误！");
        }
        return user;
    }



}
